import cn.yll.db.entity.BaseEntity;
import cn.yll.db.mapper.CommonMapper;
import cn.yll.db.service.CommonService;
import cn.yll.db.service.impl.CommonServiceImpl;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.IFill;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.TemplateType;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.baomidou.mybatisplus.generator.fill.Column;
import org.apache.ibatis.jdbc.ScriptRunner;

import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

/**
 * mybatis-plus代码生成器
 * @author yangll
 * 2022-05-25
 */
public class CodeGenerator {
    /**
     * 以下参数需要根据项目和表设置修改，模块名，数据库名，包名，表名，主键生成策略
     */
    private static final String module = "user-service/";
    private static final String dbName = "shop_user";
    private static final String packName = "cn.yll.user";
    private static final String[] tables = new String[]{"user_main"};
    private static final IdType idType = IdType.ASSIGN_ID;
    private static final String OUTPUT_DIR = System.getProperty("user.dir") + File.separator + module + "src/main/java";
    private static final List<IFill> fillList = Arrays.asList(
            new Column("create_time", FieldFill.INSERT),
            new Column("modify_time", FieldFill.INSERT_UPDATE));
    /**
     * 数据源配置
     */
    private static final DataSourceConfig.Builder DATA_SOURCE_CONFIG = new DataSourceConfig
            .Builder("jdbc:mysql://127.0.0.1:3306/" + dbName + "?socketTimeout=5000&connectTimeout=5000&useUnicode=true&characterEncoding=utf8&useSSL=false&autoConnect=true&serverTimezone=Asia/Shanghai", "root", "root");

    /**
     * 执行初始化数据库脚本
     */
    public static void before() throws SQLException {
        Connection conn = DATA_SOURCE_CONFIG.build().getConn();
        InputStream inputStream = CodeGenerator.class.getResourceAsStream("/sql/init.sql");
        ScriptRunner scriptRunner = new ScriptRunner(conn);
        scriptRunner.setAutoCommit(true);
        scriptRunner.runScript(new InputStreamReader(inputStream));
        conn.close();
    }

    /**
     * 执行 run
     */
    public static void main(String[] args) throws SQLException {
        before();
        FastAutoGenerator.create(DATA_SOURCE_CONFIG)
                // 全局配置 作者名
                .globalConfig(builder -> builder.author("yll").enableSwagger().fileOverride().disableOpenDir().outputDir(OUTPUT_DIR).commentDate("yyyy-MM-dd").dateType(DateType.TIME_PACK))
                // 包配置
                .packageConfig(builder -> builder.parent(packName))
                // 策略配置 表名，多个表名用,隔开
                .strategyConfig(builder -> builder.addInclude(tables)
                                .entityBuilder().disableSerialVersionUID().enableLombok().enableChainModel().formatFileName("%sEntity")
                                .addIgnoreColumns("id", "deleted", "create_time", "modify_time").superClass(BaseEntity.class)
                                .idType(idType).logicDeleteColumnName("deleted").addTableFills(fillList)
                                .controllerBuilder().enableRestStyle()
//                        .superClass(BaseController.class)
                                .mapperBuilder().superClass(CommonMapper.class)
                                .serviceBuilder().superServiceClass(CommonService.class).superServiceImplClass(CommonServiceImpl.class)
                )
                .templateConfig(builder -> builder.disable(TemplateType.XML))
                /*模板引擎配置，默认 Velocity 可选模板引擎 Beetl 或 Freemarker
                .templateEngine(new BeetlTemplateEngine())*/
                .templateEngine(new FreemarkerTemplateEngine())
                .execute();

    }
}
